package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
@Api(tags = "分类相关接口")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     *
     * @param category
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("添加的分类是:{}", category);
        categoryService.save(category);
        return R.success("添加分类成功");
    }

    /**
     * 分页查询分类
     *
     * @param
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.lambda().orderByDesc(Category::getUpdateTime);
        categoryService.page(categoryPage, categoryQueryWrapper);
        return R.success(categoryPage);
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping()
    public R<String> delete(Long id) {
        categoryService.removeById(id);
        return R.success("分类信息删除成功");
    }

    /**
     * 修改分类
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("分类信息修改成功");
    }


    /**
     * 新增菜品时获取所有的分类
     *
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.lambda().eq(null != category.getType(), Category::getType, category.getType());
        categoryQueryWrapper.lambda().orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(categoryQueryWrapper);
        return R.success(list);
    }


}
